<template>
 <div class="main">
  <h6>{{ $t('user.setting.form4') }}</h6>

  <el-upload
   class="avatar-uploader"
   :action="apiHost"
   v-loading="loading"
   :headers="{'acce-token': $store.getters.getToken}"
   :show-file-list="false"
   :on-success="handleAvatarSuccess"
   accept=".jpg, .png, .jpeg"
   :before-upload="beforeAvatarUpload">
   <img v-if="imageUrl" :src="imageUrl" class="avatar">
   <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
 </div>
</template>

<script>
export default {
 name: "Avatar",
 data: () => ({
  imageUrl: '',
  apiHost: '',
  loading: false
 }),
 created() {
  this.apiHost = this.$address.upload
 },
 methods: {
  handleAvatarSuccess(res, file) {
   this.$post(this.$address.editInfo, {
    data: {
     image: res.data,
     nickName: this.$store.getters.getInfo.nickName
    }
   })
    .then(e => {
     this.loading = false
     if (e.code === 1) {
      this.$get(this.$address.userInfo, {})
       .then(info => {
        if (info.code === 1) {
         this.$store.commit('setInfo', info.data)
         this.imageUrl = res.data;
        }
      })
     }
    })
  },
  beforeAvatarUpload(file) {
   const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
   const isLt2M = file.size / 1024 / 1024 < 2;

   if (!isJPG) {
    this.$message.error(this.$t('user.setting.imageType'));
   }
   if (!isLt2M) {
    this.$message.error(this.$t('user.setting.imageSize'));
   }
   if (isJPG && isLt2M) {
    this.loading = true
   }
   return isJPG && isLt2M;
  }
 }
}
</script>

<style scoped lang="scss">
.main {
 border: 1px solid rgba(0, 0, 0, 0.1);
 padding: 20px;
 border-radius: 4px;
 width: 60%;
 display: flex;
 flex-direction: column;
 margin-top: 40px;

 h6 {
  font-size: 16px;
  color: #000;
  margin-bottom: 20px;
 }

 .avatar-uploader {
  margin-right: auto;
  /deep/ .el-upload {
   border: 1px dashed #d9d9d9;
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;

   &:hover {
    border-color: #409EFF;
   }
  }
 }
 .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
 }
 .avatar {
  width: 178px;
  height: 178px;
  display: block;
 }
}
</style>
